Packer = function (w, h) {
    this.init(w, h);
};

Packer.prototype = {

    init: function (w, h) {
        this.root = {x: 0, y: 0, w: w, h: h};
    },

    fit: function (blocks) {
        var n, node, block;
        for (n = 0; n < blocks.length; n++) {
            block = blocks[n];
            node = this.findNode(this.root, block.w, block.h)

            if (node) {
                block.fit = this.splitNode(node, block.w, block.h);
            }
        }
    },

    findNode: function (root, w, h) {
        if (root.used) {
            var temp = this.findNode(root.right, w, h);
            if (!temp) {
                temp = this.findNode(root.down, w, h);
            }
            return temp;
        }
        else if ((w <= root.w) && (h <= root.h))
            return root;
        else
            return null;
    },

    splitNode: function (node, w, h) {
        node.used = true;
        node.down = {x: node.x, y: node.y + h, w: node.w, h: node.h - h};
        node.right = {x: node.x + w, y: node.y, w: node.w - w, h: h};
        return node;
    }

}


var blocks = [
    {w: 14, h: 14},
    {w: 14, h: 14},
    {w: 14, h: 14},
    {w: 14, h: 14},
    {w: 14, h: 14},
    {w: 14, h: 14},
    {w: 14, h: 14}
];
var packer = new Packer(47, 31);
packer.fit(blocks);
for (var n = 0; n < blocks.length; n++) {
    var block = blocks[n];
    if (block.fit) {
        console.log(block.w + "\r\n");
    } else {
        console.log(block.w + "remove \r\n");
    }
}